<template>
  <div class="app-container">
    <div class="app-header">
      <el-form
        v-show="showSearch"
        ref="queryForm"
        inline
        :model="queryParams"
      >
        <el-form-item
          label="部门"
          prop="deptName"
        >
          <el-input
            v-model="queryParams.deptName"
            placeholder="请输入部门名称"
            clearable
            @keyup.enter="getList"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            filterable
            placeholder="部门状态"
            clearable
          >
            <el-option
              v-for="dict in dicts[DictDirection.是否禁用字典]"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :icon="Search"
            size="small"
            @click="getList"
          >
            搜索
          </el-button>
          <el-button :icon="Refresh" size="small" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="app-mian">
      <button-tools v-model:showSearch="showSearch" @refresh="getList">
        <el-button
          type="primary"
          :icon="Plus"
          size="small"
          @click="handleAdd"
        >
          新增
        </el-button>
      </button-tools>

      <el-table
        v-loading="loading"
        border
        :data="deptList"
        row-key="deptId"
        default-expand-all
        :tree-prop="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="deptName" label="部门名称" min-width="260"></el-table-column>
        <el-table-column
          prop="orderNum"
          label="排序"
          min-width="200"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          min-width="100"
          align="center"
          :formatter="statusFormat"
        ></el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          min-width="200"
        >
          <template #default="{ row }">
            <span>{{ row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="200"
          align="center"
          class-name="small-padding fixed-width custormFixedCol"
        >
          <template #default="{ row }">
            <el-button
              v-hasPermi="['system:menu:edit']"
              type="primary"
              text
              :icon="Edit"
              @click="handleUpdate(row)"
            >
              修改
            </el-button>
            <el-button
              v-hasPermi="['system:menu:add']"
              type="primary"
              text
              :icon="Plus"
              @click="handleAdd(row)"
            >
              新增
            </el-button>
            <el-button
              v-if="row.parentId != 0"
              v-hasPermi="['system:menu:remove']"
              type="primary"
              text
              :icon="Delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      v-model="open"
      :close-on-click-modal="false"
      :title="title"
      append-to-body
    >
      <el-form
        ref="editForm"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item v-if="form.parentId != 0" label="上级部门" prop="parentId">
              <el-cascader
                ref="cascader"
                v-model="form.parentId"
                :options="deptOptions"
                :props="cascaderProps"
                clearable
                placeholder="选择上级部门"
                :show-all-levels="false"
                :normalizer="normalizer"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leaderUserId">
              <dict-select dictsName='员工'/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model.trim="form.phone" placeholder="请输入联系电话" maxlength="11"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dicts[DictDirection.是否禁用字典]" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, getCurrentInstance, watch } from 'vue'
import { ElMessage, ElMessageBox, ElButton } from 'element-plus'
import { Refresh, Search, Plus, Delete, Edit } from '@element-plus/icons-vue'
import { useI18n } from 'vue-i18n'
import { listDeptTable, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from '@/api/system/dept'
import useDicts, { DictDirection } from '@/store/modules/dicts'
import { handleTree, depClone, selectDictLabel } from '@/utils/index'
import {
  listUserTab,
} from '@/api/system/user'

const dicts = useDicts()
dicts.setDicts(DictDirection.是否禁用字典)
const queryForm = ref(null),
  queryParams = ref({
    deptName: undefined,
    status: undefined,
  }),
  showSearch = ref(true),
  loading = ref(false),
  // 标题
  title = ref(null),
  open = ref(false),
  // 部门列表
  deptList = ref(null),
  deptTreeList = ref(null)

const
  editForm = ref(null),
  {
    appContext: {
      config: {
        globalProperties: { $resetForm, $validateForm },
      },
    },
    proxy,
  } = getCurrentInstance(),
  cascaderProps = {
    checkStrictly: true,
    label: 'deptName',
    value: 'deptId',
    emitPath: false,
  },
  deptOptions = ref([]),
  rules = {
    deptName: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
    parentId: [{ required: true, message: '上级部门不能为空', trigger: 'blur' }],
    orderNum: [
      {
        required: true,
        type: 'number',
        message: '排列顺序不能为空',
        trigger: 'blur', 
      },
      {
        validator: (rule, value, callback) => {
          if (!(/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/).test(value)) {
            callback(new Error('请输入数字值'))
          } else {
            callback()
          }
        },
      },
      
    ],
    email: [
      {
        type: 'email',
        message: '请输入正确的邮箱地址',
        trigger: ['blur', 'change'],
      },
    ],
    phone: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur',
      },
    ],
  }
const form = ref({
  deptId: undefined,
  parentId: 0,
  deptName: undefined,
  orderNum: 0,
  leaderUserId: undefined,
  phone: undefined,
  email: undefined,
  status: 0,
  children: undefined,
})
// 搜索
const getList = async () => {
  loading.value = true
  const res = await listDeptTable(queryParams.value)
  try {
    if (res.code === 200) {
      deptList.value = handleTree(res.data, 'deptId')
      ElMessage.success('查询成功')
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {
    console.log(error)
    ElMessage.error(error)
  } finally {
    loading.value = false
  }
}
// 重置表单
const resetQuery = () => {
  loading.value = true
  $resetForm(queryForm.value)
}
// 重置表单
const reset = () => {
  form.value = { deptId: undefined, parentId: 0, deptName: undefined, orderNum: 0, leaderUserId: undefined, phone: undefined, email: undefined, status: 0 }
  $resetForm(editForm.value)
}
// const leaderUserOptions = ref(null)
// function getLeaderUser() {
//   listUserTab({}).then((res) => {
//     leaderUserOptions.value = res.data
//   })
// }
// 新增部门
const handleAdd = (row: { deptId?: number } | MouseEvent) => {
  reset()
  // getLeaderUser()
  if ('deptId' in row) {
    form.value.parentId = row.deptId
  } else {
    form.value.parentId = 100
  }
  title.value = '添加部门'
  open.value = true
  deptOptions.value = deptList.value
  proxy.$nextTick(() => {
    // eslint-disable-next-line no-return-assign
    listDeptTable().then(res => deptOptions.value = handleTree(res.data, 'deptId'))
  })
}
getList()
const normalizer = (node) => {
  if (node.children && !node.children.length) {
    delete node.children
  }
  return {
    id: node.deptId,
    label: node.deptName,
    children: node.children,
  }
}
const handleUpdate = (row: { [key: string]: any }) => {
  open.value = true
  title.value = '更新部门'
  getLeaderUser()
  getDept(row.deptId).then(res => {
    form.value = res.data
  })
  proxy.$nextTick(() => {
    // eslint-disable-next-line no-return-assign
    listDeptExcludeChild(row.deptId).then((res) => (deptOptions.value = handleTree(res.data, 'deptId')))
  })
}
const handleDelete = (row) => {
  ElMessageBox.confirm(`是否确认删除名称为"${ row.deptName }"的数据项？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => {
    delDept(row.deptId)
  })
  .then(() => {
    ElMessage.success('删除成功')
    getList()
  })
  .catch((err) => console.log(err))
}
const submitForm = () => {
  $validateForm(editForm.value, () => {
    if (form.value && form.value.children) form.value.children = undefined
    if (form.value.deptId != undefined) {
      updateDept(form.value).then((res) => {
        if (res.code == 200) {
          ElMessage.success('修改成功')
          open.value = false
          loading.value = true
          getList()
        }
      })
    } else {
      addDept(form.value).then((res) => {
        if (res.code == 200) {
          ElMessage.success('新增成功')
          reset()
          open.value = false
          loading.value = true
          getList()
        }
      })
    }
  })
}
const cancel = () => {
  reset()
  open.value = false
  ElMessage.info('取消操作')
}
const statusFormat = (row) => dicts.getDictLabel({ dict: DictDirection.是否禁用字典, value: row.status })
</script>
<style lang="less" scoped>
.app-header {
  height: 100px;
  background-color: #fff;
  border: 1px solid #fff;
  border-radius: 10px;
  overflow: hidden;
  margin: 10px 0;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
}
.app-mian {
  height: auto;
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
  padding-bottom: 10px;
  margin-bottom: 10px;
}
</style>
